package com.new1cloud.file.upload.client.bootstrap;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class BufferedRandomAccessFile extends RandomAccessFile {
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 1024 * 100; // 100MB
    private MappedByteBuffer buffer;

    public BufferedRandomAccessFile(String fileName, String mode, Long startPosition) throws IOException {
        super(fileName, mode);
        // 获取与该文件关联的FileChannel对象
        FileChannel fileChannel = this.getChannel();
        // 映射整个文件到内存中
        final long fileSize = this.length();
        if(startPosition < fileSize) {
            buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startPosition,
                    Math.min(DEFAULT_BUFFER_SIZE, fileSize - startPosition));
        }
    }

    @Override
    public void close() throws IOException {
        // 清除并解除映射缓冲区
        if (buffer != null) {
            buffer.clear();
        }
        super.close();
    }

    // 重写read和write方法，使用缓冲区进行操作
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        // 从缓冲区读取数据
//        buffer.position(off);
        buffer.get(b, off, len);
        return buffer.remaining() > 0 ? len : buffer.remaining();
    }
}
